package com.stanwind.netty.core.protocol.codc;

import com.stanwind.netty.constant.ServerSetting;
import com.stanwind.netty.core.protocol.model.Request;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;


/**
 * 请求编码对象
 *
 * @author westwind
 */
public class RequestEncoder extends OneToOneEncoder {

    @Override
    protected Object encode(ChannelHandlerContext context, Channel channel,
                            Object obj) throws Exception {
        Request request = (Request) (obj);

        // 获取一个动态buffer
        ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();

        // 开始写数据

        // 写包头 4
        buffer.writeInt(ServerSetting.FLAG);

        //time 4
        buffer.writeInt(request.getTime());

        // length 2
        buffer.writeShort(request.getLength());

        // cmd 2
        buffer.writeShort(request.getCmd());

        // data
        if (request.getData() != null) {
            buffer.writeBytes(request.getData());
        }

        return buffer;
    }

}
